
import {getAccess,getState,getPkgRandomId} from "./util";
import { getHttpUrl} from "./env.config";
import {appInfo } from "./appinfo"

function request(url, data, method, authHeader){
	if(url.substring(0,1) != "/")
			url = "/api/"+ url;
		else
			url = "/api"+ url;
	url = getHttpUrl() + url;

//	console.log("authHeader:" + authHeader)
	if(authHeader === undefined) {
		authHeader =  getState()
	
		if(authHeader === undefined || authHeader == null || authHeader.trim().length <= 0){
			authHeader = "Basic c2V2ZW5zZXhhcHA6Y0dsM25PbkJwWnc9PQ==";
		} else {	
			authHeader = "Bearer " + authHeader;
		}
	}
//	console.log("authHeader:" + authHeader)
		
	return new Promise(function(resolver, reject) {

		uni.request({
			url: url,
			data: data,
			method: method,
			dataType: "json",
			header:{
				"Authorization": authHeader,
				"timeStamp": new Date().getTime(),
				"clientType":appInfo.clientType,
				"deviceId": appInfo.deviceId,
				"appKey":appInfo.appKey,
				"appSecret": appInfo.appSecret,
			},
			success: function(res){
				//console.log(JSON.stringify(res));
				if(res.statusCode == 200){
					resolver(res.data)
				} else if(res.statusCode == 40301){
					reject({
						errorType: "is not auth",
						res: res
					})
				} else if(res.statusCode == 401) {
					reject({
						errorType: "未授权",
						res: res
					})
				}
			
//				console.log("success:"+url);
				reject({
                    errorType: 'status_error',
                    res: res
                })
			},
			error: function(e){
				console.log("error:"+url+JSON.stringify(e)+"；测试:"+ url);
				reject({
					errorType: 'onerror',
					e: e
				})
			},
			method: method,
			complete: function(){
//				console.log(url)
//				console.log("uni.request complete....")
			}
		})
	});
}


module.exports = {
	request: request
}